package org.blogwu.learn.threadLearn.自己实现一个重入锁.使用AQS;

public class MyLockTest2 {
    static MyLock reentrantLock = new MyLock();

    // 必须加volatile，否则有可见性问题
    static volatile int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLock.lock();
                System.out.println("t1 获取了锁");
                try {
                    Thread.sleep(25000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2尝试获取锁");
                reentrantLock.lock();
                try {
                    System.out.println("t2获取锁");
                    Thread.sleep(25000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
            }
        });
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
            }
        });
        t1.setName("t1");
        t2.setName("t2");
        t2.setName("t3");
        t1.start();
        t2.start();
        t3.start();

        System.out.println("i= " + i);
    }
}
